package cake.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cake.bean.Comment;
import cake.db.MySqlDb;

/**
 * 用户评论Dao
 * @author Administrator
 *
 */
public class CommentDao {
private MySqlDb db=new MySqlDb();
	
	//获取评论
	public Comment getComment(long id)
	{
		Comment comment=null;
		String sql="select * from comment where id="+id;
		try {
			ResultSet rs = db.query(sql);
			while(rs.next())
			{
				comment=new Comment();
				comment.setId(rs.getLong("id"));
				comment.setContent(rs.getString("content"));
				comment.setOccurTime(rs.getString("occurTime"));
				comment.setUserid(rs.getLong("userid"));
				comment.setOrderid(rs.getLong("orderid"));
				comment.setType(rs.getInt("type"));
				break;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally
		{
			db.Close();
		}
		
		return comment;
	}
	
	/**
	 * 获取评论列表
	 * @param currPage 当前页
	 * @param pageSize	页大小
	 * @param where		条件
	 * @return
	 */
	public List<Comment> getComments(int currPage,int pageSize,String where)
	{
		List<Comment> comments=new ArrayList<Comment>();
		String sql="select * from comment ";
		if(!where.equals(""))
		{
			sql+=" Where "+where;
		}
		if(pageSize!=0)
		{
			sql+=" limit "+((currPage-1)*pageSize)+","+pageSize;
		}
		try {
			ResultSet rs = db.query(sql);
			while(rs.next())
			{
				Comment comment=new Comment();
				comment.setId(rs.getLong("id"));
				comment.setContent(rs.getString("content"));
				comment.setOccurTime(rs.getString("occurTime"));
				comment.setUserid(rs.getLong("userid"));
				comment.setOrderid(rs.getLong("orderid"));
				comment.setType(rs.getInt("type"));
				
				comments.add(comment);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally
		{
			db.Close();
		}
		
		return comments;
	}
	/**
	 * 添加评论	
	 * @param Comment
	 * @return
	 */
	public boolean addComment(Comment comment)
	{
		String sql="insert into comment(userid,content,occurTime,orderid,type) values("+comment.getUserid()+",'"+comment.getContent()+"','"+comment.getOccurTime()+"',"+comment.getOrderid()+","+comment.getType()+")";
		try
		{
			int row = db.execute(sql);
			
			return row>0?true:false;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}finally
		{
			db.Close();
		}
		return false;
		
	}

	/**
	 * 删除评论
	 * @param Comment
	 * @return
	 */
	public  boolean deleteComment(Comment comment)
	{
		Comment oldMsg=getComment(comment.getId());
		
		if(oldMsg==null)
		{
			return false;
		}
		
		String sql="Delete from comment where id="+comment.getId();
		
		try
		{
			int row = db.execute(sql);
			
			return row>0?true:false;
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}finally
		{
			db.Close();
		}
		return false;
	}
}
